# -*- coding: UTF-8 -*-
'''
Created on 2011-1-24

@author: sumory
'''
import os
from utils import my_utils


def encrypt(dir,outfile,suffix,recursion):
    if suffix=='.*':
        all_type=True
    else:
        all_type=False
        exts = suffix.split("|")
    all_files=[]
    dir=dir.encode('gbk')
    print('传入的目录：'+dir.decode('gbk'))
    #当前递归的目录，当前递归的目录下的所有子目录，当前递归的目录下的所有文件
    for root, dirs, files in os.walk(dir):
        for name in files:
            file_path=unicode(os.path.join(root,name),'gbk')#全称,正确地取得windows下的中文文件名
            extension=os.path.splitext(file_path)[1]
           
            if extension[:1]!='.':
                extension='.'+extension
            oldfile=file_path
            extensionlen=-len(extension)
            newfile=oldfile[:extensionlen]+'-new'+extension
            if all_type:
                os.rename(oldfile, newfile)
                all_files.append('/'.join(file_path.split('\\'))+"<>"+'/'.join(newfile.split('\\')))
            else:
                if extension in exts: 
                    os.rename(oldfile, newfile)
                    all_files.append('/'.join(file_path.split('\\'))+"<>"+'/'.join(newfile.split('\\')))
        if(not recursion):
            break
    if len(all_files)>0:
        file = open(outfile,"w")
        try:
            print('successfully writes %d lines(files).' %len(all_files))   
            all_files.insert(0, '#共写入：'+str(len(all_files))+'行')
            all_files.insert(0, '#生成时间：'+my_utils.getCurTime())
            all_files.insert(0, '#源加密路径：'+dir.decode('gbk').encode('utf-8'))
            towrite='\n'.join(all_files)
            file.write(towrite) 
        finally:
            file.close()
        return towrite
    else:
        file = open(outfile,"w")
        try:
            nothintowrite='#源加密路径：'+dir.decode('gbk').encode('utf-8')+'\n#生成时间：'+my_utils.getCurTime()+'\n#共写入0行'
            file.write(nothintowrite)
        finally:
            file.close()
        print('sorry,no files found!')
        return nothintowrite.decode('utf-8')
          
def decrypt(logfile):
    try:#如果传入的是非文件路径（目录）则需异常
        file = open(logfile,"r")
        filecounts=0
        try:
            for line in file:
                if line.startswith('#'):
                    continue
                maps=line.rstrip('\n').split('<>')
                #split后编码非中文，用utf-8解码(本来文件就是以utf-8编码保存的)
                #os.rename('/'.join(unicode(maps[1],'utf-8').split('\\')),'/'.join(unicode(maps[0],'utf-8').split('\\')))
                os.rename(unicode(maps[1],'utf-8').encode('gbk'),unicode(maps[0],'utf-8').encode('gbk'))
                filecounts=filecounts+1
                #os.rename若是路径错误或文件不存在那会发生什么？
            print('successfully recovers %d files.' %filecounts)
        except:
            return 'Exception'
        finally:
            file.close()
    except:
        return 'Exception'
    return ('解密成功'+str(filecounts)+'行').decode('utf-8')   

def invoke():
    #dir=unicode("D:/allfiles/备份/a",'gbk')千万别想反了，要编码而不是解码
    #dir="D:/allfiles/"
    #dir="D:/allfiles/备份/a".encode('gbk')
    dir="D:/allfiles/备份"
    outfile="D:/binaries.dat"
    suffix = ".c|.cpp"
    encrypt(dir,outfile,suffix,1)

#invoke()
#decrypt("D:\\qbconfig\\2011-01-31 16-03-43.txt")

